import NotFound from "@/views/error/NotFound.vue";
import pkIndex from "@/views/pk/pkIndex.vue";
import rankListIndex from "@/views/ranklist/rankListIndex.vue"
import recordIndex from "@/views/record/recordIndex.vue";
import userBotsIndex from "@/views/user/bots/userBotsIndex.vue"
import {createRouter, createWebHistory} from "vue-router";
import LoginIndex from "@/views/user/account/LoginIndex.vue";
import RegisterIndex from "@/views/user/account/RegisterIndex.vue";
import store from "@/store/index";
import RecordContent from "@/views/record/RecordContent.vue";

const routes = [

    {
        path: "/pk",
        name: "pk",
        component: pkIndex,
        meta: {
            requestAuth: true,
        }

    },
    {
        path: "/ranklist",
        name: "ranklist",
        component: rankListIndex,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: "/record",
        name: "record",
        component: recordIndex,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: "/record/:recordId",
        name:"record_content",
        component: RecordContent,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: "/mybots",
        name: "mybots",
        component: userBotsIndex,
        meta: {
            requestAuth: true,
        }
    },
    {
        path: "/user/account/login",
        name: "login",
        component: LoginIndex,
        meta: {
            requestAuth: false,
        }
    },
    {
        path: "/user/account/register",
        name: "register",
        component: RegisterIndex,
        meta: {
            requestAuth: false,
        }
    },
    {
        path: "/404",
        name: "404",
        component: NotFound,
        meta: {
            requestAuth: false,
        }
    },
    {
        path: "/",
        name: "home",
        redirect: "/pk",
    },
    {
        path: "/:catchAll(.*)",
        redirect: "/404",
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    // 如果目标路由不需要授权，则直接放行
    if (to.meta.requestAuth === false) {
        next();
        return;
    }

    const jwt_token = localStorage.getItem("jwt_token");

    // 如果有 JWT token
    if (jwt_token) {
        store.commit("updateToken", jwt_token);
        store.dispatch("getinfo", {
            success() {
                next();
            },
            error() {
                next({ name: "login" });
            }
        });
    } else {
        // 如果没有 JWT token，检查是否需要授权
        if (to.meta.requestAuth && !store.state.user.is_login) {
            next({ name: "login" });
        } else {
            next();
        }
    }
});


export default router;
